import axios from 'axios';
import { API_BASE_URL } from '../config';

const api = axios.create({
  baseURL: API_BASE_URL,
  headers: {
    'Content-Type': 'application/json'
  }
});

// 添加请求拦截器，自动添加 token
api.interceptors.request.use(config => {
  const token = localStorage.getItem('token');
  if (token) {
    config.headers.Authorization = `Bearer ${token}`;
  }
  return config;
});

export const materialOrderService = {
  // 创建材料订单
  createOrder: async (materialId, customerInfo) => {
    try {
      const response = await api.post('/api/material-orders', {
        materialId,
        customerInfo
      });
      return response.data;
    } catch (error) {
      throw error.response?.data || error.message;
    }
  },

  // 获取订单详情
  getOrderDetails: async (orderNumber) => {
    try {
      const response = await api.get(`/api/material-orders/${orderNumber}`);
      return response.data;
    } catch (error) {
      throw error.response?.data || error.message;
    }
  },

  // 生成下载令牌
  generateDownloadToken: async (orderNumber) => {
    try {
      const response = await api.post(`/api/material-orders/${orderNumber}/download-token`);
      return response.data;
    } catch (error) {
      throw error.response?.data || error.message;
    }
  },

  // 验证下载令牌
  verifyDownloadToken: async (orderNumber, token) => {
    try {
      const response = await api.get(`/api/material-orders/${orderNumber}/verify-token/${token}`);
      return response.data;
    } catch (error) {
      throw error.response?.data || error.message;
    }
  },

  // 获取用户订单列表
  getUserOrders: async (page = 1, limit = 10) => {
    try {
      const response = await api.get('/api/material-orders/user/orders', {
        params: { page, limit }
      });
      return response.data;
    } catch (error) {
      throw error.response?.data || error.message;
    }
  },

  // 更新订单状态（管理员）
  updateOrderStatus: async (orderNumber, status) => {
    try {
      const response = await api.patch(`/api/material-orders/${orderNumber}/status`, { status });
      return response.data;
    } catch (error) {
      throw error.response?.data || error.message;
    }
  },

  // 创建支付订单
  createPayment: async (orderNumber, paymentMethod) => {
    try {
      const response = await api.post('/api/payment/create', {
        orderNumber,
        paymentMethod
      });
      return response.data;
    } catch (error) {
      throw error.response?.data || error.message;
    }
  },

  // 查询支付状态
  queryPaymentStatus: async (orderId) => {
    try {
      const response = await api.get(`/api/payment/status/${orderId}`);
      return response.data;
    } catch (error) {
      throw error.response?.data || error.message;
    }
  }
};